<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>数据录入</title>
  <!-- 重置样式，使得各浏览器样式更一致 -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.1/normalize.min.css">
  <!-- vant样式 -->
  <link rel="stylesheet" href="https://fastly.jsdelivr.net/npm/vant@4/lib/index.css" />
  <!-- 自定义样式 -->
  <link rel="stylesheet" href="../style/common.css" />
</head>

<body>
  <div id="DataInput" class="road-survey-input">
    <div class="road-survey-header">
      <van-tabs v-model:active="activeTab">
        <van-tab v-for="item in headerList" :title="item.value">
        </van-tab>
      </van-tabs>
    </div>
    <!-- 基础信息填写页面 -->
    <template v-if="activeTab === 0">
      <div class="road-survey-direction">
        <van-cell-group inset>
          <van-field label="勘察时间" v-model="baseMsg.time" input-align="right">
            <template #button>
              <van-button size="mini" @click="handleGetTime">更新</van-button>
            </template>
          </van-field>
          <van-field label="记录人" v-model="baseMsg.user" placeholder="请输入记录人" input-align="right"></van-field>
          <van-field label="路口名称" v-model="baseMsg.roadName" placeholder="请输入路口名称" input-align="right"></van-field>
          <van-field label="路口经纬度" v-model="baseMsg.roadPosition" placeholder="请输入路口经纬度" input-align="right">
            <template #button>
              <van-button size="mini" @click="gotoGetLocal">获取</van-button>
            </template>
          </van-field>
          <van-cell title="点位形状" title-class="cell-title">
            <van-radio-group v-model="baseMsg.roadShape" direction="horizontal">
              <van-radio :name="road.key" icon-size="18px" v-for="road in ROAD_SHAPE">
                <template v-if="road.showInput && baseMsg.roadShape === road.key">
                  <van-field :label="road.value" v-model="baseMsg.roadShapeExt" input-align="left">
                  </van-field>
                </template>
                <template v-else>
                  {{road.value}}
                </template>
              </van-radio>
            </van-radio-group>
          </van-cell>
          <van-cell title="点位属性" title-class="cell-title">
            <van-radio-group v-model="baseMsg.dotType" direction="horizontal">
              <van-radio :name="dot.key" icon-size="18px" v-for="dot in DOT_TYPE">{{dot.value}}</van-radio>
            </van-radio-group>
          </van-cell>
          <van-cell title="信号机品牌" title-class="cell-title" v-if="!isRoadWay">
            <van-radio-group v-model="baseMsg.signalType" direction="horizontal">
              <van-radio :name="signal.key" icon-size="18px" v-for="signal in SIGNAL_TYPE">
                <template v-if="signal.showInput && baseMsg.signalType === signal.key">
                  <van-field :label="signal.value" v-model="baseMsg.signalTypeExt" input-align="left">
                  </van-field>
                </template>
                <template v-else>
                  {{signal.value}}
                </template>
              </van-radio>
            </van-radio-group>
          </van-cell>
          <van-cell title="周围建筑物" title-class="cell-title">
            <van-checkbox-group v-model="baseMsg.aroundBuilding" shape="square" class="small-label">
              <van-checkbox :name="around.key" icon-size="18px" :label-disabled="true"
                v-for="around in AROUND_BUILDING">
                <template v-if="around.showInput && baseMsg.aroundBuilding.includes(around.key)">
                  <van-field :label="around.value" v-model="baseMsg.aroundBuildingExt" input-align="left">
                  </van-field>
                </template>
                <template v-else>
                  {{around.value}}
                </template>
              </van-checkbox>
            </van-checkbox-group>
          </van-cell>
        </van-cell-group>
      </div>
    </template>
    <template v-else>
      <div class="road-survey-direction" v-if="directionMsg.length">
        <div class="direction-left">
          <van-sidebar v-model="directionMsg[activeTab - 1].current">
            <van-sidebar-item :title="item.value" v-for="item in showDirectionConfig"
              :key="item.key"></van-sidebar-item>
          </van-sidebar>
        </div>
        <div class="direction-right">
          <van-cell-group>
            <template v-for="item in currentDirChild.child" :key="item.key">
              <!-- 如果选择了“无”，关联的信息不显示出来 -->
              <template v-if="!(item.hiddenKey && currentDirItem[item.relativeKey] === item.hiddenKey)">
                <!-- 车道特殊处理 -->
                <template v-if="item.key==='motorwayNumber'">
                  <van-cell :title="item.value" title-class="cell-title">
                    <van-radio-group>
                      <van-stepper v-model="currentDirItem.motorwayNumber" @plus="handleChangeMotNumber(1)"
                        @minus="handleChangeMotNumber(-1)"></van-stepper>
                    </van-radio-group>
                  </van-cell>
                  <template v-for="(road, index) in currentDirItem.motorwayList">
                    <van-cell :title="'车道' + (index + 1)">
                    </van-cell>
                    <van-steps direction="vertical" :active="4">
                      <van-step>
                        <van-field label="车道宽度" v-model="road.width" type="number" input-align="right">
                          <template #button>米</template>
                        </van-field>
                      </van-step>
                      <van-step>
                        <van-field label="转向" readonly input-align="right"></van-field>
                        <div class="direction-img-content">
                          <div v-for="item in DIRECTION_IMAGE" :key="item.key"
                            @click="handleChangeDirection(item, road)"
                            :class="['direction-img-item', {'active': road.direction.includes(item.key)}]">
                            <img
                              :src="`../images/${road.direction.includes(item.key) ? 'active-' : ''}${item.value}.png`" />
                          </div>
                        </div>
                      </van-step>
                    </van-steps>
                  </template>
                </template>
                <!-- radio类型的综合 -->
                <template v-else-if="item.type===CONTENT_TYPE.RADIO">
                  <!-- 无title时，将标题宽度设置为0 -->
                  <van-cell :title="item.value" :title-class="item.value ? 'cell-title' : 'none-title'">
                    <van-radio-group v-model="currentDirItem[item.key]" class="flex-end">
                      <van-radio :name="road.key" icon-size="18px" v-for="road in item.option">
                        <template v-if="road.showInput && currentDirItem[item.key] === road.key">
                          <van-field :label="road.value" v-model="currentDirItem[item.key + 'Ext']" input-align="left">
                          </van-field>
                        </template>
                        <template v-else>
                          {{road.value}}
                        </template>
                      </van-radio>
                    </van-radio-group>
                  </van-cell>
                </template>
                <template v-else-if="item.type===CONTENT_TYPE.CHECKBOX">
                  <van-cell :title="item.value" :title-class="item.value ? 'cell-title' : 'none-title'">
                    <van-checkbox-group v-model="currentDirItem[item.key]" shape="square">
                      <van-checkbox :name="around.key" icon-size="18px" :label-disabled="true"
                        v-for="around in item.option">
                        <template v-if="around.showInput && currentDirItem[item.key].includes(around.key)">
                          <van-field :label="around.value" v-model="currentDirItem[item.key + 'Ext']"
                            input-align="left">
                          </van-field>
                        </template>
                        <template v-else>
                          {{around.value}}
                        </template>
                      </van-checkbox>
                    </van-checkbox-group>
                  </van-cell>
                </template>
                <template v-else>
                  <van-field :label="item.value" v-model="currentDirItem[item.key]" :placeholder="`请输入`"
                    :input-align="item.value ? 'right': 'left'" :type="item.inputType || 'number'" rows="5"
                    autosize></van-field>
                </template>
              </template>
            </template>
          </van-cell-group>
        </div>
      </div>
    </template>
    <!-- 添加方向 -->
    <van-popup v-model:show="showAddPicker" destroy-on-close round position="bottom">
      <van-picker :model-value="pickerDirectionValue" :columns="canUseDirection"
        :columns-field-names="{text: 'value', value: 'key'}" title="添加方向" @cancel="showAddPicker = false"
        @confirm="handleSureAdd" />
    </van-popup>

    <van-floating-bubble axis="xy" icon="add" magnetic="x" @click="handleAddDirection" />
  </div>
</body>
<script src="https://fastly.jsdelivr.net/npm/vue@3"></script>
<script src="https://fastly.jsdelivr.net/npm/vant@4/lib/vant.min.js"></script>
<script src="../js/methods.js"></script>
<script>
  const { createApp, ref, nextTick, reactive, onMounted, onUnmounted, computed, watch } = Vue
  const app = Vue.createApp({
    setup() {
      // 当前激活栏的tab
      const activeTab = ref(0)

      // 顶部选择器
      const headerList = ref([baseHeader])

      // 基础信息
      const baseMsg = ref(JSON.parse(JSON.stringify(base)))

      /**
       * 是否路段
       * 如果点位形状选择了“路段”，则后面不显示“信号机品牌”、“信号灯杆”、“机动车信号灯”等栏的输入项
       */
      const isRoadWay = computed(() => {
        return baseMsg.value.roadShape === LD_KEY
      })

      // 需要填写的数据，因为路段时候会过滤一些信息
      const showDirectionConfig = computed(() => {
        let list = JSON.parse(JSON.stringify(DIRECTION_CONFIG))
        list = list.filter(item => !(item.hiddenKey?.includes(LD_KEY) && isRoadWay.value))
        return list
      })

      // 当前方向的绑定的值信息
      const currentDirItem = computed(() => {
        return directionMsg.value[activeTab.value - 1]
      })

      // 当前方向的基础展示信息
      const currentDirChild = computed(() => {
        return showDirectionConfig.value[currentDirItem.value.current]
      })

      // 获取当前可以添加的方向，已经被添加的不可二次添加
      const canUseDirection = computed(() => {
        const headerListMap = headerList.value.map(item => item.key)
        const list = JSON.parse(JSON.stringify(DIRECTION_OPTIONS))
        list.forEach(item => {
          item.disabled = headerListMap.includes(item.key)
        })
        return list
      })

      // 方向信息的全量
      const directionMsg = ref([])

      /**
       * 修改当前的转向信息
       * @item  当前点击的数据
       * @road 维护的数据
       */
      const handleChangeDirection = (item, road) => {
        const result = road.direction.findIndex(roadItem => roadItem === item.key)
        if (result > -1) {
          road.direction.splice(result, 1)
          return
        }
        road.direction.push(item.key)
      }

      /**
       * 点击增加或者减少车道
       * @number 1 增加 -1 减少
       */
      const handleChangeMotNumber = (number) => {
        if (number > 0) {
          currentDirItem.value.motorwayList.push(JSON.parse(JSON.stringify(motorwayItem)))
        }
        else {
          currentDirItem.value.motorwayList.pop()
        }
      }

      // 展示弹窗
      const showAddPicker = ref(false)
      // 点击添加的按钮
      const handleAddDirection = () => {
        showAddPicker.value = true
      }

      const pickerDirectionValue = ref()

      const timer = ref(null)
      // 确认添加
      const handleSureAdd = (data) => {
        if (data.selectedOptions.length) {
          headerList.value.push({ key: data.selectedOptions[0].key, value: data.selectedOptions[0].value })
          directionMsg.value.push(JSON.parse(JSON.stringify(directionItem)))
        }
        showAddPicker.value = false
      }

      const handleGetTime = () => {
        baseMsg.value.time = formatDate(new Date())
      }

      // local存储
      const setLocalMsg = () => {
        setLocal('baseMsg', baseMsg.value)
        setLocal('directionMsg', directionMsg.value)
        setLocal('headerList', headerList.value)
        setLocal('activeTab', activeTab.value)
      }

      // local获取
      const getLocalMsg = () => {

        baseMsg.value = getLocal('baseMsg') || JSON.parse(JSON.stringify(base))
        directionMsg.value = getLocal('directionMsg') || []
        headerList.value = getLocal('headerList') || [baseHeader]
        setTimeout(() => {
          activeTab.value = getLocal('activeTab')
        }, 100)
      }

      /** 获取路口名称和经纬度 */
      const gotoGetLocal = () => {
        const url = window.location.origin + '/html/getPosition.html'
        window.top.location.href = url
      }

      // 页面卸载
      const pageUnload = () => {
        setLocalMsg()
        timer.value && clearInterval(timer.value)
      }

      onMounted(async () => {
        getLocalMsg()
        // 每5秒自动更新缓存
        timer.value = setInterval(() => {
          setLocalMsg()
        }, 5 * 1000)
        // 监听iframe卸载事件
        window.addEventListener('beforeunload', () => {
          pageUnload()
        });
      })

      // 页面销毁时，先进行数据的保存
      onUnmounted(() => {
        pageUnload()
      })

      return {
        // 外部导入的内容导出
        ROAD_SHAPE, DOT_TYPE, SIGNAL_TYPE, AROUND_BUILDING, CONTENT_TYPE, LD_KEY,
        DIRECTION_IMAGE,
        // 基础定义的内容导出
        headerList, baseMsg, activeTab, directionMsg, showAddPicker, pickerDirectionValue,
        // computed计算属性导出
        currentDirChild, currentDirItem, canUseDirection, isRoadWay, showDirectionConfig,
        // 方法导出
        handleChangeDirection, handleChangeMotNumber, handleAddDirection, handleSureAdd, handleGetTime, gotoGetLocal
      }
    }
  })
  app.use(vant);
  app.use(vant.Lazyload);
  app.mount("#DataInput");
</script>

</html>